﻿using MediatR;
using PublicClass;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;
using S.Services.SheepMale.Read.Api.Application.ReadCommand.ReadMarketCommand;

namespace S.Services.SheepMale.Read.Api.Application.ReadCommandHandler.ReadMarketCommandHandler
{
    public class MarketShowCommandHandler : IRequestHandler<MarketShowCommand, PageInfo<EntityMarket>>
    {
        private readonly IRepository<EntityMarket> repository;

        private readonly PageInfo<EntityMarket>  pageInfo;
        public MarketShowCommandHandler(IRepository<EntityMarket> repository, PageInfo<EntityMarket> pageInfo)
        {
            this.repository = repository;
            this.pageInfo = pageInfo;
        }

        public async Task<PageInfo<EntityMarket>> Handle(MarketShowCommand request, CancellationToken cancellationToken)
        {
            var result = await repository.AllAsync();

            if (request.sdate!=null)
            {
                var date1 = Convert.ToDateTime(request.sdate);
                result = result.Where(x => x.MarketDate >= date1);
            }
            if (request.edate != null)
            {
                var date2 = Convert.ToDateTime(request.edate).AddHours(24);
                result = result.Where(x => x.MarketDate <= date2);
            }
            if (!string.IsNullOrEmpty(request.client))
            {
                result = result.Where(x => x.Client == request.client);
            }
            if (!string.IsNullOrEmpty(request.DocumentNumber))
            {
                result = result.Where(x => x.DocumentNumber.Contains(request.DocumentNumber));
            }
            if (!string.IsNullOrEmpty(request.DepartmentId))
            {
                result = result.Where(x => x.DepartmentId== request.DepartmentId);
            }
            if (!string.IsNullOrEmpty(request.MarketAddress))
            {
                result = result.Where(x => x.MarketAddress == request.MarketAddress);
            }
            if (!string.IsNullOrEmpty(request.SellPeople))
            {
                result = result.Where(x => x.SellPeople == request.SellPeople);
            }
            if (request.AuditState != 0)
            {
                result = result.Where(x => x.AuditState == request.AuditState);
            }
            pageInfo.totalCount = result.Count();
            pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
            pageInfo.datas = result.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return pageInfo;
        }
    }
}
